package com.dt.app.api.product.service.impl;

import com.dt.app.modules.product.entities.Category;
import com.dt.app.modules.product.vo.CategoryBean;
import com.dt.app.api.product.mapper.CategoryMapper;
import com.dt.app.api.product.service.ICategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 鸿源塔基
 * @since 2024-03-05
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {

    public List<CategoryBean> buildTree(List<CategoryBean> list, Integer cid){
        List<CategoryBean> children = list.stream().filter(x -> x.getParentId().equals(cid)).collect(Collectors.toList());
        List<CategoryBean> subclass = list.stream().filter(x -> !x.getParentId().equals(cid)).collect(Collectors.toList());
        if(children.size() > 0){
            children.forEach(x -> {
                if(subclass.size() > 0){
                    buildTree(subclass,x.getCategoryId()).forEach(
                            y -> x.getChildren().add(y)
                    );
                }
            });
        }
        return children;
    }
    //最多4层
    public String getPathName(Integer parentId){
        try{
            if(parentId.intValue()==0)return "";
            StringBuffer stringBuffer=new StringBuffer();
            Category category1=this.getById(parentId);
            stringBuffer=stringBuffer.append(category1.getCname()+"-->");
            if(category1.getParentId().intValue()==0)
                return stringBuffer.toString();
            Category category2=this.getById(category1.getParentId());
            stringBuffer=stringBuffer.append(category2.getCname()+"-->");
            if(category2.getParentId().intValue()==0)
                return stringBuffer.toString();
            Category category3=this.getById(category2.getParentId());
            stringBuffer=stringBuffer.append(category3.getCname()+"-->");
            if(category3.getParentId().intValue()==0)
                return stringBuffer.toString();
            Category category4=this.getById(category3.getParentId());
            stringBuffer=stringBuffer.append(category4.getCname()+"-->");
            return stringBuffer.toString();
        }catch (Exception e){
            e.printStackTrace();
        }
        return "";
    }
}
